package cn.scw.project.facility.service.impl;

import cn.scw.common.ValidateUtil;
import cn.scw.common.exception.CustomException;
import cn.scw.common.utils.StringUtils;
import cn.scw.common.utils.bean.ToolUtils;
import cn.scw.common.utils.pay.MD5Util;
import cn.scw.framework.redis.RedisCache;
import cn.scw.project.facility.domain.FacPrintPriceFacility;
import cn.scw.project.facility.domain.netework.bean.FacPrintPriceAddReq;
import cn.scw.project.facility.domain.netework.bean.FacPrintPriceFacilityAddReq;
import cn.scw.project.facility.domain.netework.bean.FacPrintPriceFacilityFindReq;
import cn.scw.project.facility.domain.vo.FacPrintPriceResVo;
import cn.scw.project.facility.domain.vo.FacPrintPriceVo;
import cn.scw.project.facility.mapper.FacPrintPriceFacilityMapper;
import cn.scw.project.facility.service.IFacPrintPriceFacilityService;
import cn.scw.project.facility.service.IFacPrintPriceService;
import cn.scw.project.facility.service.IFacPrintTypeService;
import cn.scw.project.system.service.ISysDictDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 设备打印价格Service业务层处理
 *
 * @author api
 * @date 2020-05-20
 */
@Service
public class FacPrintPriceFacilityServiceImpl implements IFacPrintPriceFacilityService {
    private static final Logger logger = LoggerFactory.getLogger(FacPrintPriceFacilityServiceImpl.class);

    @Autowired
    private FacPrintPriceFacilityMapper facPrintPriceFacilityMapper;

    @Autowired
    private IFacPrintPriceService iFacPrintPriceService;

    @Autowired
    private ISysDictDataService iSysDictDataService;

    @Autowired
    private IFacPrintTypeService iFacPrintTypeService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询设备打印价格
     *
     * @param id 设备打印价格ID
     * @return 设备打印价格
     */
    @Override
    public FacPrintPriceFacility selectFacPrintPriceFacilityById(Long id) {
        return facPrintPriceFacilityMapper.selectFacPrintPriceFacilityById(id);
    }

    @Override
    public FacPrintPriceVo selectFacPrintPriceFacilityVoById(Long id) {
        return facPrintPriceFacilityMapper.selectFacPrintPriceFacilityVoById(id);
    }

    /**
     * 查询设备打印价格列表
     *
     * @return 设备打印价格
     */
    @Override
    public List<FacPrintPriceResVo> selectFacPrintPriceFacilityList(String code) {
        List<FacPrintPriceVo> list = facPrintPriceFacilityMapper.selectFacPrintPriceFacilityList(code);
        return iFacPrintPriceService.listToResVo(list);
    }

    /**
     * 新增设备打印价格
     *
     * @param reqList 设备打印价格
     * @return 结果
     */
    @Override
    public synchronized int insertFacPrintPriceFacility(List<FacPrintPriceFacilityAddReq> reqList) {
        for (FacPrintPriceFacilityAddReq req : reqList) {

            if (StringUtils.isBlank(req.getFacilityCode()))
                throw new CustomException("请选择设备");
            if (req.getColorPrice() == null && req.getNoColorPrice() == null)
                throw new CustomException("请设置正确的价格");
            if (StringUtils.isBlank(req.getType()))
                throw new CustomException("请选择打印类型");
            if (!iFacPrintTypeService.existsByCode(req.getType()))
                throw new CustomException("请选择正确的打印类型");
            if (req.getIsDoubleFaced() == null)
                req.setIsDoubleFaced(false);
//                throw new CustomException("请选择是否双面");
            if (req.getPaperNumber() == null || req.getPaperNumber() < 1)
                throw new CustomException("请输入正确的纸张数");
            if (req.getColorId() != null) {
                FacPrintPriceFacility facPrintPrice = this.selectFacPrintPriceFacilityById(req.getColorId());
                facPrintPrice.setPrice(req.getColorPrice());
                if (facPrintPrice.getPaperNumber() != req.getPaperNumber())
                    if (this.existsByCodeTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(facPrintPrice.getFacilityCode(), facPrintPrice.getType(), facPrintPrice.getIsColours(), facPrintPrice.getIsDoubleFaced(), facPrintPrice.getPaperNumber()))
                        throw new CustomException("已存在此设置的价格");
                facPrintPrice.setPaperNumber(req.getPaperNumber());
                facPrintPriceFacilityMapper.updateFacPrintPriceFacility(facPrintPrice);
            } else if (req.getColorPrice() != null && req.getColorPrice() > 0) {
                FacPrintPriceFacility facility = new FacPrintPriceFacility();
                ToolUtils.copyPropertiesIgnoreNull(req, facility);
                facility.setIsColours(true);
                facility.setPrice(req.getColorPrice());
                if (this.existsByCodeTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(facility.getFacilityCode(), facility.getType(), facility.getIsColours(), facility.getIsDoubleFaced(), facility.getPaperNumber()))
                    throw new CustomException("已存在此设置的价格");
                facPrintPriceFacilityMapper.insertFacPrintPriceFacility(facility);
            }

            if (req.getNoColorId() != null) {
                FacPrintPriceFacility facPrintPrice = this.selectFacPrintPriceFacilityById(req.getNoColorId());
                facPrintPrice.setPrice(req.getNoColorPrice());
                if (facPrintPrice.getPaperNumber() != req.getPaperNumber())
                    if (this.existsByCodeTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(facPrintPrice.getFacilityCode(), facPrintPrice.getType(), facPrintPrice.getIsColours(), facPrintPrice.getIsDoubleFaced(), facPrintPrice.getPaperNumber()))
                        throw new CustomException("已存在此设置的价格");
                facPrintPrice.setPaperNumber(req.getPaperNumber());
                facPrintPriceFacilityMapper.updateFacPrintPriceFacility(facPrintPrice);
            } else if (req.getNoColorPrice() != null && req.getNoColorPrice() > 0) {
                FacPrintPriceFacility facility = new FacPrintPriceFacility();
                ToolUtils.copyPropertiesIgnoreNull(req, facility);
                facility.setIsColours(false);
                facility.setPrice(req.getNoColorPrice());
                if (this.existsByCodeTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(facility.getFacilityCode(), facility.getType(), facility.getIsColours(), facility.getIsDoubleFaced(), facility.getPaperNumber()))
                    throw new CustomException("已存在此设置的价格");
                facPrintPriceFacilityMapper.insertFacPrintPriceFacility(facility);
            }
        }
//        }
        return 1;
    }

    /**
     * 修改设备打印价格
     *
     * @param req 设备打印价格
     * @return 结果
     */
    @Override
    public int updateFacPrintPriceFacility(FacPrintPriceAddReq req) {
        FacPrintPriceFacility facPrintPriceFacility = this.selectFacPrintPriceFacilityById(req.getId());
        if (facPrintPriceFacility == null)
            throw new CustomException("打印价格不存在");
        ToolUtils.copyPropertiesIgnoreNull(req, facPrintPriceFacility);

        if (!iFacPrintTypeService.existsByCode(facPrintPriceFacility.getType()))
            throw new CustomException("请选择正确的打印类型");
        if (facPrintPriceFacility.getPaperNumber() < 1)
            throw new CustomException("请输入正确的纸张数");
        if (facPrintPriceFacility.getPrice() <= 0)
            throw new CustomException("请设置正确的价格");
        if (this.existsByCodeTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(facPrintPriceFacility.getFacilityCode(), facPrintPriceFacility.getType(), facPrintPriceFacility.getIsColours(), facPrintPriceFacility.getIsDoubleFaced(), facPrintPriceFacility.getPaperNumber()))
            throw new CustomException("已存在此设置的价格");

        return facPrintPriceFacilityMapper.updateFacPrintPriceFacility(facPrintPriceFacility);
    }

    /**
     * 批量删除设备打印价格
     *
     * @param ids 需要删除的设备打印价格ID
     * @return 结果
     */
    @Override
    public int deleteFacPrintPriceFacilityByIds(Long[] ids) {
        return facPrintPriceFacilityMapper.deleteFacPrintPriceFacilityByIds(ids);
    }

    /**
     * 删除设备打印价格信息
     *
     * @param id 设备打印价格ID
     * @return 结果
     */
    @Override
    public int deleteFacPrintPriceFacilityById(Long id) {
        return facPrintPriceFacilityMapper.deleteFacPrintPriceFacilityById(id);
    }

    @Override
    public boolean existsByCodeTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(String facilityCode, String type, boolean isColours, boolean isDoubleFaced, int paperNumber) {
        return facPrintPriceFacilityMapper.existsByCodeTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(facilityCode, type, isColours, isDoubleFaced, paperNumber);
    }

    @Override
    public FacPrintPriceVo selectByFacilityCodeAndTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(String facilityCode, String type, boolean isColours, boolean isDoubleFaced, int paperNumber) {
        isDoubleFaced = false;
        FacPrintPriceVo facPrintPrice = facPrintPriceFacilityMapper.selectByFacilityCodeAndTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(facilityCode, type, isColours, isDoubleFaced, paperNumber);
        if (facPrintPrice == null) {
            logger.info("selectByFacilityCodeAndTypeAndIsColoursAndIsDoubleFacedAndPaperNumber facPrintPrice is null");
            return iFacPrintPriceService.selectByTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(type, isColours, isDoubleFaced, paperNumber);
        }

        return facPrintPrice;
    }


    @Override
    public FacPrintPriceVo selectByFacilityCodeAndTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(FacPrintPriceFacilityFindReq req) {
        logger.info("FacPrintPriceVo printfile=" + req.getPrintfile());
//        if (StringUtils.isBlank(req.getFacilityCode()))
//            throw new CustomException("请选择设备");
        if (StringUtils.isBlank(req.getType()))
            throw new CustomException("请选择类型");
        if (req.getIsColours() == null)
            throw new CustomException("请选择打印颜色");
        if (req.getCount() == null)
            throw new CustomException("请输入打印份数");
//        if (req.getPrintfile() == null)
//            throw new CustomException("请选择打印文件");

        int printPageNum = 1;
        if (req.getPrintfile() != null) {
            String strType = req.getType();
            int nType = 0;
            if (strType != null && !strType.equalsIgnoreCase("")) nType = Integer.parseInt(strType);
            printPageNum = ValidateUtil.wordPage(req.getPrintfile(), nType);
            if (printPageNum < 1) throw new CustomException("打印页数不能少于1页");
            logger.info("FacPrintPriceVo printPageNum=" + printPageNum);
            req.setStartPage(1);
            req.setEndPage(printPageNum);
        }
        req.initData();
        FacPrintPriceVo result = this.selectByFacilityCodeAndTypeAndIsColoursAndIsDoubleFacedAndPaperNumber(req.getFacilityCode(), req.getType(), req.getIsColours(), req.getIsDoubleFaced(), req.getPaperNumber());

        result.setPrice( BigDecimal.valueOf(printPageNum) .multiply(BigDecimal.valueOf(result.getPrice())).doubleValue());
        result.setPaperNumber(printPageNum);

        String redisKey = MD5Util.MD5Encode(req.getFacilityCode() + req.getPrintfile(), "utf-8");
        redisCache.setCacheObject(redisKey, printPageNum, 20, TimeUnit.MINUTES);
        return result;
    }
}
